<script lang="ts">
  let { apiRoute, currentRequestMethod } = $props()
  import { sineIn } from 'svelte/easing'
  import {
    Button,
    ButtonGroup,
    Dropdown,
    DropdownLi,
    DropdownUl,
    Input,
    uiHelpers,
    Spinner,
  } from 'svelte-5-ui-lib'
  import { ChevronDownOutline, LaptopCodeOutline } from 'flowbite-svelte-icons'
  import { httpMethods } from '$lib/const'
  import { api, urlJoin } from '$lib/api/client'
  import { getContext } from 'svelte'
  import { BaseUrlContext} from '$lib/const.js'
  import type { BaseUrlItem } from '$lib/api/types'
  import type { Writable } from 'svelte/store'
  import { requestStore, FullURL, APIResponse } from '$lib/utils/stores.svelte'
  
  let currentEnv = getContext(BaseUrlContext) as Writable<BaseUrlItem>

  $effect(() => {
    const env = $currentEnv
    if (env && env.url && apiRoute){
      FullURL.set(urlJoin(env.url , apiRoute))
    }
  })

  let isPending = $state(false)
  let uihelpers = uiHelpers()

  // 创建响应式方法
  const togglePending = (value: boolean) => {
    isPending = value
  }
</script>

<ButtonGroup class="w-full mb-4">
  <Button
    onclick={uihelpers.toggle}
    size="xs"
    class="min-w-24 text-xs p-1 dark:bg-gray-600 text-orange-600 hover:text-orange-800 border-none  dark:hover:text-orange-600 dark:bg-gray-500 "
  >
    {currentRequestMethod}
    <ChevronDownOutline class="h-4 w-4" />
  </Button>
  <div class="relative">
    <Dropdown
      dropdownStatus={uihelpers.isOpen}
      closeDropdown={uihelpers.close}
      params={{ y: 0, duration: 200, easing: sineIn }}
      class="absolute -top-2 right-26 w-26"
      onclick={uihelpers.toggle}
    >
      <DropdownUl>
        {#each httpMethods as method}
          <DropdownLi href="#" onclick={() => (currentRequestMethod = method)}>{method}</DropdownLi>
        {/each}
      </DropdownUl>
    </Dropdown>
  </div>
  <Input bind:value={$FullURL} size="md" class="border-none bg-gray-50 text-md text-gray-900" />

  {#if isPending}
    <Button
      color="gray"
      class="!p-2.5 w-32"
      size="xs"
      type="button"
      onclick={() => {
        togglePending(false)
        api.cancelRequest($FullURL, currentRequestMethod)
      }}
    >
      <Spinner class="me-3" size="4" color="teal" />Cancel
    </Button>
  {:else}
    <Button
      color="primary"
      class="!p-2.5 w-32"
      size="xs"
      type="button"
      onclick={() => {
        togglePending(true)
        api
          .request({
            url: $FullURL,
            method: currentRequestMethod,
            ...$requestStore,
          })
          .then((data) => {
            APIResponse.set(data)
          })
          .catch((error) => {
            console.error('error', error)
          })
          .finally(() => {
            togglePending(false)
          })
      }}
    >
      <LaptopCodeOutline class="h-5 w-5 mr-1" />Test
    </Button>
  {/if}
</ButtonGroup>
